#define _CRT_SECURE_NO_WARNINGS 1

#include"linklist.h"

ListNode* ListCreat(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc error");
		exit(-1);
	}
	newnode->val = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	
	return newnode;
}

void ListPrint(ListNode* phead)
{
	assert(phead);
	printf("head");
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf(" <=> %d", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

ListNode* ListInit()
{
	ListNode* phead = ListCreat(-1);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void ListDestory(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = NULL;
		cur = next;
	}
	free(phead);
	phead = NULL;
}

void ListPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* tail = phead->prev;
	ListNode* newnode = ListCreat(x);
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* next = phead->next;
	ListNode* newnode = ListCreat(x);
	phead->next = newnode;
	newnode->next = next;
	next->prev = newnode;
	newnode->prev = phead;
}

void ListPopBack(ListNode* phead)
{
	assert(phead);

	ListNode* tail = phead->prev;
	phead->prev = tail->prev;
	tail->prev->next = phead;
	free(tail);
	tail = NULL;
}

void ListPopFront(ListNode* phead)
{
	assert(phead);

	ListNode* next = phead->next;
	phead->next = next->next;
	next->next->prev = phead;
	free(next);
	next = NULL;
}

ListNode* ListFind(ListNode* phead, LTDataType x)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->val == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);

	ListNode* prev = ListCreat(x);
	pos->prev->next = prev;
	prev->prev = pos->prev;
	prev->next = pos;
	pos->prev = prev;
}

void ListErase(ListNode* pos)
{
	assert(pos);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}